from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()

class Workflow(models.Model):
    name = models.CharField(max_length=100, verbose_name="工作流名称")
    description = models.TextField(verbose_name="描述", blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "工作流"
        verbose_name_plural = verbose_name

class WorkflowNode(models.Model):
    NODE_TYPES = (
        ('start', '开始节点'),
        ('end', '结束节点'),
        ('task', '任务节点'),
        ('condition', '条件节点'),
        ('parallel', '并行节点'),
    )
    
    workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE, related_name='nodes')
    name = models.CharField(max_length=100, verbose_name="节点名称")
    node_type = models.CharField(max_length=20, choices=NODE_TYPES, verbose_name="节点类型")
    next_nodes = models.ManyToManyField('self', blank=True, symmetrical=False)
    timeout = models.IntegerField(null=True, blank=True, verbose_name="超时时间(分钟)")
    handlers = models.ManyToManyField(User, blank=True, related_name='handling_nodes', verbose_name="处理人")
    condition_expression = models.TextField(blank=True, verbose_name="条件表达式")
    
    class Meta:
        verbose_name = "工作流节点"
        verbose_name_plural = verbose_name


class WorkflowInstance(models.Model):
    STATUS_CHOICES = (
        ('pending', '待处理'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('terminated', '已终止'),
    )
    
    workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE)
    current_node = models.ForeignKey(WorkflowNode, on_delete=models.CASCADE)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name = "工作流实例"
        verbose_name_plural = verbose_name

class WorkflowHistory(models.Model):
    instance = models.ForeignKey(WorkflowInstance, on_delete=models.CASCADE, related_name='histories')
    node = models.ForeignKey(WorkflowNode, on_delete=models.CASCADE)
    action_user = models.ForeignKey(User, on_delete=models.CASCADE)
    action_time = models.DateTimeField(auto_now_add=True)
    action_data = models.JSONField(default=dict)
    comment = models.TextField(blank=True)

    class Meta:
        verbose_name = "工作流历史"
        verbose_name_plural = verbose_name
        ordering = ['-action_time']
